﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ASPNETPerformance.App_BusinessLogic.Helpers;
using Microsoft.Samples.Web;

namespace ASPNETPerformance.App_BusinessLogic.HttpModules {
    public class SpriteImageOptimizationModule : IHttpModule {
        private static readonly object _lockObj = new object();
        private static bool _hasAlreadyRun;
        public const string SpriteFolderRelativePath = "~/_assets/img/Sprites/";

        [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0" )]
        public void Init( HttpApplication context ) {
            if ( CommonHelper.GetCookieBool( "IsSpriteImageOptimizationModule" ) ) {
                lock ( _lockObj ) {
                    if ( _hasAlreadyRun )
                        return;
                    else
                        _hasAlreadyRun = true;
                }
            }
            HttpRuntime.Cache.Insert( "spriteFolderRelativePath", SpriteFolderRelativePath );
            ImageOptimizations.AddCacheDependencies( context.Context.Server.MapPath( SpriteFolderRelativePath ), rebuildImages: true );

            return;
        }

        public void Dispose() {
        }
    }
}
